package com.ken.apollo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ken.apollo.domain.bo.ContactInquiryBo;
import com.ken.apollo.domain.entity.ContactInquiry;
import com.ken.apollo.domain.query.ContactInquiryQuery;
import com.ken.apollo.domain.vo.ContactInquiryVo;
import com.ken.apollo.mapper.ContactInquiryMapper;
import com.ken.apollo.service.ContactInquiryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
 * 联系咨询服务实现类
 *
 * @author Ken
 * @since 2024-01-01
 */
@Slf4j
@Service
public class ContactInquiryServiceImpl extends ServiceImpl<ContactInquiryMapper, ContactInquiry> implements ContactInquiryService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean submitInquiry(ContactInquiryBo bo) {
        try {
            ContactInquiry entity = new ContactInquiry();
            
            // 处理姓名字段：如果name不为空，则将name拆分为firstName和lastName
            if (bo.getName() != null && !bo.getName().trim().isEmpty()) {
                String fullName = bo.getName().trim();
                // 如果包含空格，拆分为firstName和lastName
                if (fullName.contains(" ")) {
                    int lastSpaceIndex = fullName.lastIndexOf(" ");
                    entity.setFirstName(fullName.substring(0, lastSpaceIndex));
                    entity.setLastName(fullName.substring(lastSpaceIndex + 1));
                } else {
                    // 如果没有空格，将整个名称作为firstName
                    entity.setFirstName(fullName);
                    entity.setLastName("");
                }
            } else {
                // 如果name为空，保持原有的firstName和lastName为空
                entity.setFirstName("");
                entity.setLastName("");
            }
            
            // 设置其他字段
            entity.setEmail(bo.getEmail() != null ? bo.getEmail().trim() : "");
            entity.setPhone("");
            entity.setCompany(bo.getCompany() != null ? bo.getCompany().trim() : "");
            entity.setSubject("");
            entity.setMessage(bo.getMessage() != null ? bo.getMessage().trim() : "");
            entity.setIpAddress(bo.getIpAddress());
            entity.setUserAgent(bo.getUserAgent());

            // 设置默认状态为待处理
            entity.setStatus(ContactInquiry.Status.PENDING.getCode());

            // 如果newsletter为null，设置为false
            entity.setNewsletter(false);

            // 确保时间字段被设置（作为备用方案）
            LocalDateTime now = LocalDateTime.now();
            if (entity.getCreateTime() == null) {
                entity.setCreateTime(now);
            }
            if (entity.getUpdateTime() == null) {
                entity.setUpdateTime(now);
            }
            
            boolean result = save(entity);
            
            if (result) {
                log.info("联系咨询提交成功，ID: {}, 邮箱: {}, 主题: {}", 
                    entity.getId(), entity.getEmail(), entity.getSubject());
            }
            
            return result;
        } catch (Exception e) {
            log.error("提交联系咨询失败", e);
            throw new RuntimeException("提交联系咨询失败: " + e.getMessage());
        }
    }

    @Override
    public IPage<ContactInquiryVo> queryPage(ContactInquiryQuery query) {
        Page<ContactInquiryVo> page = new Page<>(query.getPageNum(), query.getPageSize());
        return baseMapper.selectContactInquiryPage(page, query);
    }

    @Override
    public List<ContactInquiryVo> queryList(ContactInquiryQuery query) {
        return baseMapper.selectContactInquiryList(query);
    }

    @Override
    public ContactInquiryVo queryById(Long id) {
        return baseMapper.selectContactInquiryById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateStatus(Long id, String status) {
        try {
            ContactInquiry entity = new ContactInquiry();
            entity.setId(id);
            entity.setStatus(status);
            
            boolean result = updateById(entity);
            
            if (result) {
                log.info("联系咨询状态更新成功，ID: {}, 新状态: {}", id, status);
            }
            
            return result;
        } catch (Exception e) {
            log.error("更新联系咨询状态失败，ID: {}", id, e);
            throw new RuntimeException("更新联系咨询状态失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchUpdateStatus(List<Long> ids, String status) {
        try {
            LambdaQueryWrapper<ContactInquiry> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(ContactInquiry::getId, ids);
            
            ContactInquiry entity = new ContactInquiry();
            entity.setStatus(status);
            
            boolean result = update(entity, wrapper);
            
            if (result) {
                log.info("批量更新联系咨询状态成功，数量: {}, 新状态: {}", ids.size(), status);
            }
            
            return result;
        } catch (Exception e) {
            log.error("批量更新联系咨询状态失败", e);
            throw new RuntimeException("批量更新联系咨询状态失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        try {
            boolean result = removeById(id);
            
            if (result) {
                log.info("删除联系咨询成功，ID: {}", id);
            }
            
            return result;
        } catch (Exception e) {
            log.error("删除联系咨询失败，ID: {}", id, e);
            throw new RuntimeException("删除联系咨询失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchDelete(List<Long> ids) {
        try {
            boolean result = removeByIds(ids);
            
            if (result) {
                log.info("批量删除联系咨询成功，数量: {}", ids.size());
            }
            
            return result;
        } catch (Exception e) {
            log.error("批量删除联系咨询失败", e);
            throw new RuntimeException("批量删除联系咨询失败: " + e.getMessage());
        }
    }

    @Override
    public List<ContactInquiryVo> getStatusStatistics() {
        return baseMapper.selectStatusStatistics();
    }

    @Override
    public List<ContactInquiryVo> getSubjectStatistics() {
        return baseMapper.selectSubjectStatistics();
    }

    @Override
    public Long getPendingCount() {
        LambdaQueryWrapper<ContactInquiry> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ContactInquiry::getStatus, ContactInquiry.Status.PENDING.getCode());
        return count(wrapper);
    }

    @Override
    public Long getTodayCount() {
        LocalDateTime startOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        LocalDateTime endOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
        
        LambdaQueryWrapper<ContactInquiry> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(ContactInquiry::getCreateTime, startOfDay, endOfDay);
        return count(wrapper);
    }
}
